package cn.edu.bistu.photoeditingtools;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import android.content.ContentResolver;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.ColorMatrix;
import android.graphics.ColorMatrixColorFilter;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

    private Button toGray;
    private Button antiWise;
    private Button clockWise;
    private Button merge;

    private ImageView imageView;

    private static final String IMAGE_TYPE = "image/*";     //表示获取到的文件的类型
    private static final int OPERATION_TOGRAYSCALE = 0;   //请求码，表示进行转换成黑白的操作
    private static final int OPERATION_ANTIWISE = 1;    //表示逆时针旋转的操作
    private static final int OPERATION_CLOCKWISE = 2;   //表示瞬时针旋转的操作
    private static final int OPERATION_MERGE = 3;    //表示合并的操作
    private static final int MERGE_CHOOSE = 4;      //合并操作选择的第二张图片

    private Bitmap bitmap;  //用户选择的图片
    private Bitmap beMergeBitmap;    //合并操作用户选择的第二张图片


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initView();


    }


    //为各个按钮设置的监听器
    private View.OnClickListener operation = new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            int id = view.getId();
            Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
            intent.setType(IMAGE_TYPE);
            switch (id) {
                case R.id.btn_toGray:
                    startActivityForResult(intent, OPERATION_TOGRAYSCALE);
                    break;
                case R.id.btn_antiWise:
                    startActivityForResult(intent, OPERATION_ANTIWISE);
                    break;
                case R.id.btn_clockWise:
                    startActivityForResult(intent, OPERATION_CLOCKWISE);
                    break;
                case R.id.btn_merge:
                    startActivityForResult(intent, OPERATION_MERGE);
                    break;


            }


        }
    };


    //根据请求码判断选择的是哪种操作，以获取intent的内容
    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (resultCode != RESULT_OK){
            //若返回的结果（用户选择的图片）不等于RESULT_OK的话，说明不是图像，则无法进行下一步操作
            Toast.makeText(MainActivity.this,"返回的结果出错",Toast.LENGTH_SHORT);
            return;
        }

        ContentResolver resolver = getContentResolver();
        Uri originalUri = data.getData();
        switch (requestCode){
            case OPERATION_TOGRAYSCALE:
                try {
                    bitmap = MediaStore.Images.Media.getBitmap(resolver,originalUri);
                    bitmap = toGrayScale(bitmap);
                    imageView.setImageBitmap(bitmap);

                } catch (Exception e){
                    e.printStackTrace();
                }
                break;
            case OPERATION_ANTIWISE:
                try {
                    bitmap = MediaStore.Images.Media.getBitmap(resolver,originalUri);
                    bitmap = bimapRotation(bitmap,270);     //逆时针旋转90度即旋转270度
                    imageView.setImageBitmap(bitmap);


                }catch (Exception e){
                    e.printStackTrace();
                }
                break;
            case OPERATION_CLOCKWISE:
                try {
                    bitmap = MediaStore.Images.Media.getBitmap(resolver,originalUri);
                    bitmap = bimapRotation(bitmap,90);
                    imageView.setImageBitmap(bitmap);

                }catch (Exception e){
                    e.printStackTrace();
                }
                break;
            case OPERATION_MERGE:
                try {
                    bitmap = MediaStore.Images.Media.getBitmap(resolver,originalUri);   //保存选择的第一张图像
                    Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
                    intent.setType(IMAGE_TYPE);
                    startActivityForResult(intent,MERGE_CHOOSE);

                }catch (Exception e){
                    e.printStackTrace();
                }
                break;
            case MERGE_CHOOSE:
                try {
                    beMergeBitmap = MediaStore.Images.Media.getBitmap(resolver,originalUri);    //保存选择的第二张图像
                    bitmap = mergeBitmap(bitmap,beMergeBitmap);
                    imageView.setImageBitmap(bitmap);

                }catch (Exception e){
                    e.printStackTrace();
                }
                break;



        }

    }

    //初始化组件
    private void initView() {
        toGray = findViewById(R.id.btn_toGray);
        antiWise = findViewById(R.id.btn_antiWise);
        clockWise = findViewById(R.id.btn_clockWise);
        merge = findViewById(R.id.btn_merge);

        imageView = findViewById(R.id.imageView);

        toGray.setOnClickListener(operation);
        antiWise.setOnClickListener(operation);
        clockWise.setOnClickListener(operation);
        merge.setOnClickListener(operation);


    }


    //图片变黑白(即灰)
    public static Bitmap toGrayScale(Bitmap original) {
        //获取宽高
        int width, height;
        height = original.getHeight();
        width = original.getWidth();

        Bitmap bmpGray = Bitmap.createBitmap(width, height, Bitmap.Config.RGB_565);   //设置目标位图为8位RGB位图
        Canvas c = new Canvas(bmpGray); //在目标位图上创建画布
        Paint paint = new Paint();  //添加画笔
        ColorMatrix colorMatrix = new ColorMatrix();    //颜色矩阵，用来设置色彩

        colorMatrix.setSaturation(0);   //设置色彩饱和度为0
        ColorMatrixColorFilter f = new ColorMatrixColorFilter(colorMatrix);   //滤色器
        paint.setColorFilter(f);

        c.drawBitmap(original, 0, 0, paint);


        return bmpGray;
    }

    //实现图片旋转效果
    public Bitmap bimapRotation(Bitmap original, final int degree) {
        Matrix matrix = new Matrix();
        matrix.setRotate(degree);
        int width = original.getWidth();
        int height = original.getHeight();

        Bitmap bmp = Bitmap.createBitmap(original,0,0,width,height,matrix,true);
        Paint paint = new Paint();
        Canvas canvas = new Canvas(bmp);
        canvas.drawBitmap(bmp, matrix, paint);

/*
        float targetX, targetY;
        if (degree == 90) {
            targetX = original.getHeight();
            targetY = 0;
        } else if (degree == 270) {
            targetX = 0;
            targetY = original.getWidth();
        } else {
            targetX = original.getHeight();
            targetY = original.getWidth();
        }

        final float[] values = new float[9];
        matrix.getValues(values);

        float x1 = values[Matrix.MTRANS_X];
        float y1 = values[Matrix.MTRANS_Y];

        matrix.postTranslate(targetX - x1, targetY - y1);

        Bitmap bmp = Bitmap.createBitmap(original.getHeight(), original.getWidth(), original.getConfig());
        Paint paint = new Paint();
        Canvas canvas = new Canvas(bmp);

        canvas.drawBitmap(bmp, matrix, paint);*/

        return bmp;
    }


    //实现将两张图片拼接为一张图片
    public Bitmap mergeBitmap(Bitmap firstBitmap,Bitmap secondBitmap){
        Bitmap bitmap;
        int width = firstBitmap.getWidth(); //以第一张图片的宽度为基准对第二张图片进行等比缩放
        if (secondBitmap.getWidth()!=width){
            int h2 = secondBitmap.getHeight()*width / secondBitmap.getWidth();
            bitmap = Bitmap.createBitmap(width,firstBitmap.getHeight()+h2,Bitmap.Config.ARGB_8888);
            Canvas canvas = new Canvas(bitmap);
            Bitmap newSizeBitmap = resizeBitmap(secondBitmap,width,h2);
            canvas.drawBitmap(firstBitmap,0,0,null);
            canvas.drawBitmap(newSizeBitmap,0,firstBitmap.getHeight(),null);

        } else {
            //若两张图片宽度相等则直接拼接
            bitmap = Bitmap.createBitmap(width,firstBitmap.getHeight()+secondBitmap.getHeight(),Bitmap.Config.ARGB_8888);
            Canvas canvas = new Canvas(bitmap);
            canvas.drawBitmap(firstBitmap,0,0,null);
            canvas.drawBitmap(secondBitmap,0,firstBitmap.getHeight(),null);

        }
        return bitmap;

    }

    //缩放第二张图
    public Bitmap resizeBitmap(Bitmap secondBitmap, int newWidth, int newHeight) {
        //缩放比
        float scaleWidth = ((float) newWidth) / secondBitmap.getWidth();
        float scaleHeight = ((float) newHeight) / secondBitmap.getHeight();

        Matrix matrix = new Matrix();
        matrix.postScale(scaleWidth,scaleHeight);   //缩放方法
        return Bitmap.createBitmap(secondBitmap,0,0,secondBitmap.getWidth(),secondBitmap.getHeight(),matrix,true);

    }


}